package com.zhazha.earlybird.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zhazha.earlybird.beans.CompanyInfo;

public class CompanyDAO {

	private SQLiteDatabase mDatabase;
	private static final String COMPANY_TABLE = "company";
	
	private static final String COMPANY_ID 				= "id";
	private static final String COMPANY_NAME				= "name";
	private static final String COMPANY_NATION_ID		= "nation_id";
	
	private static final int COMPANY_ID_INDEX 				= 0;
	private static final int COMPANY_NAME_INDEX			= 1;
	private static final int COMPANY_NATION_ID_INDEX		= 2;
	
	CompanyDAO(SQLiteDatabase db) {
		mDatabase = db;
	}
	
	
	public boolean insert(CompanyInfo company) {
		
		try {
			ContentValues cv = new ContentValues();
			cv.put(COMPANY_ID, 	company.getId());
			cv.put(COMPANY_NAME,   company.getName());
			cv.put(COMPANY_NATION_ID, company.getNationId());
			
			this.mDatabase.insert(COMPANY_TABLE, null, cv);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	public boolean delete(int id) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.delete(COMPANY_TABLE, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean update(int id, ContentValues cv) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.update(COMPANY_TABLE, cv, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public CompanyInfo queryById(int id) {
		CompanyInfo company = null;
		
		try {
			String selection = "id=?";
			String[] selectionArgs = {String.valueOf(id)};
			Cursor c = this.mDatabase.query(COMPANY_TABLE, null, selection, selectionArgs, null, null, null);
			
			if(c.moveToFirst()) {
				company = new CompanyInfo();
				company.setId(c.getInt(COMPANY_ID_INDEX));
				company.setName(c.getString(COMPANY_NAME_INDEX));
				company.setNationId(c.getInt(COMPANY_NATION_ID_INDEX));
			}
			
			return company;
			
		}catch (Exception e) {
			e.printStackTrace();
			return company;
		}
	}
}
